var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var se_type = $("#se_type").val();
var api = frameElement.api, W = api.opener;
var callback = api.data.callback,oper = api.data.oper;
var detailUrl = config.BASEPATH+'batch/sell/temp_loadproduct/'+se_type;
var saveUrl = config.BASEPATH+'batch/sell/temp_save/'+se_type;


$.fn.subtext=function(value,count,txt){	
	if (value.length>count){
		if (txt==null){txt='..'}
		$(this).text(value.substring(0,count)+txt);
		$(this).attr('title',value); 
	}else{
		$(this).text(value);
	}    
};
$.fn.subval=function(value,count){	
	if (value.length>count){
		$(this).val(value.substring(0,count));
		$(this).attr('title',value); 
	}else{
		$(this).val(value);
	}    
};

var handle = {
	save:function(){
		var products = updateDatas.get();
		var unitPrice = $("#unitPrice_show").val();
		if(isNaN(unitPrice)){
			unitPrice = $("#unitPrice").text()
		}
		var temp_unitPrice = $("#temp_unitPrice").val();
		if (products.length == 0 && !(temp_unitPrice != '' && parseFloat(unitPrice) != parseFloat(temp_unitPrice))){
			api.close();
			return;
		}
		var postData = {};
		if(temp_unitPrice != '' && parseFloat(unitPrice) != parseFloat(temp_unitPrice)){//此时需要更新临时表中该商品的价格
			postData.unitPrice = unitPrice;
			postData.pd_code = product.pd_code;
		}
		postData.products = products;
		$("#btnSave").attr("disabled",true);
		$.ajax({
			type:"POST",
			url:saveUrl,
			data:JSON.stringify(postData),
			cache:false,
			dataType:"json",
			contentType:"application/json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : '保存成功'});
					setTimeout("api.close()", 300);
				}else{
					Public.tips({type: 1, content : data.message});
				}
				$("#btnSave").attr("disabled",false);
			}
		});
	}
};

var chkVaildateStock,chkRealStock,chkUseableStock,chkGift;
var columnsOriginal = null;
var rowsOriginal = null;

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initEvent();
		this.loadDetailGrid();
	},
	initDom:function(){
		if(system.USEABLE == 1){//启用可用库存
			$("#chkUseableStock").show();
		}else{
			$("#chkUseableStock").hide();
		}
		chkVaildateStock=$("#chkVaildateStock").cssCheckbox();
		chkRealStock=$("#chkRealStock").cssCheckbox();
		chkUseableStock=$("#chkUseableStock").cssCheckbox();
		if(api.data.sel_pi_type == 1){//赠品
			$("#unitPrice_show").attr("disabled",true);
			$("#isGift").text("赠品");
			$("#chkGift_Input").prop("checked","checked");
		}
		chkGift=$("#chkGift").cssCheckbox();
	},
	buildDetailUrlParams:function(){
		var params = '';
		params += 'pd_code='+api.data.pd_code;
		params += '&dp_code='+api.data.dp_code;
		params += '&exist=1';
		params += '&gift='+api.data.sel_pi_type;
		params += '&priceType='+api.data.priceType;
		params += '&ci_rate='+api.data.ci_rate;
		params += '&batch_price='+api.data.batch_price;
		params += '&ci_code='+api.data.ci_code;
		return params;
	},
	loadDetailGrid:function(){
		$("#btnSave").show();
    	$("#btnExit").show();
    	$("#ProductInfo").show();
		$.ajax({
			type:"POST",
			url:detailUrl+'?'+THISPAGE.buildDetailUrlParams(),
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					$('#sizeDetail').GridUnload();
					product=data.data.product;
					THISPAGE.initDetailDom();
					THISPAGE.initDetailGrid(data.data.columns,data.data.rows);
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
	},
	initDetailDom:function(){
		var _self = this;
		this.selectCell={iRow:0,iCol:0,rowid:0,value:''};
		if($.trim(product.pdm_img_path) != ''){
			$("#ProductPhoto").attr("src",$("#serverPath").val()+product.pdm_img_path);
		}else{
			$("#ProductPhoto").attr("src",config.BASEPATH+'resources/grid/images/nophoto.png');
		}
		$('#pd_no').text(product.pd_no);
		$('#pd_name').subtext(product.pd_name,10);
		$('#pd_season').text(product.pd_season);
		$('#pd_year').text(product.pd_year);
		$('#tp_name').subtext($.trim(product.pd_tp_name),4);
		$('#bd_name').subtext($.trim(product.pd_bd_name),4);
		$('#last_batch_price').val(product.last_batch_price);
		$('#pd_sell_price').val(product.pd_sell_price);
		$('#unitPrice_show').val(product.unitPrice);
		$('#unitPrice').text(product.unitPrice);
		$('#temp_unitPrice').val($.trim(product.temp_unitPrice));
		$('#temp_rebatePrice').val($.trim(product.temp_rebatePrice));
		this.loadMorePrice();
	},
	loadMorePrice:function(){
		$('#ulPrice').empty();
		$('#ulPrice').append("<li onclick='THISPAGE.priceMoreClick("+product.last_batch_price+")'><span>最近批发价：</span>￥"+product.last_batch_price+"</li>");
		$('#ulPrice').append("<li onclick='THISPAGE.priceMoreClick("+product.pd_batch_price+")'><span>批发价：</span>￥"+product.pd_batch_price+"</li>");
		$('#ulPrice').append("<li onclick='THISPAGE.priceMoreClick("+product.pd_batch_price1+")'><span>批发价1：</span>￥"+product.pd_batch_price1+"</li>");
		$('#ulPrice').append("<li onclick='THISPAGE.priceMoreClick("+product.pd_batch_price2+")'><span>批发价2：</span>￥"+product.pd_batch_price2+"</li>");
		$('#ulPrice').append("<li onclick='THISPAGE.priceMoreClick("+product.pd_batch_price3+")'><span>批发价3：</span>￥"+product.pd_batch_price3+"</li>");
		$('#ulPrice').append("<li onclick='THISPAGE.priceMoreClick("+product.pd_sell_price+")'><span>零售价：</span>￥"+product.pd_sell_price+"</li>");
		$('#ulPrice').append("<li onclick='THISPAGE.priceMoreClick("+product.pd_cost_price+")'><span>成本价：</span>￥"+product.pd_cost_price+"</li>");
	},
	priceMoreClick:function(price){
		$('#divPriceMore').css('display','none');
		var sel_pi_type = chkGift.chkVal().join() ? 1 : 0;
		if(sel_pi_type == 1){
			return;
		}
		$('#unitPrice_show').val(price);
		$('#unitPrice').val(price);
	},
	initDetailGrid:function(columns,rows){
		updateDatas.clear();//清空json中临时数据
		columnsOriginal = columns;
		rowsOriginal = rows;
		var _self=this;
		var colModel = [
	    	{label:'颜色', name: 'cr_name',index: '', width: 100,fixed:true},
	    	{name:'cr_code',hidden:true},
	    	{label:'杯型', name: 'br_name',index: '', width: 100,fixed:true},
	    	{name:'br_code',hidden:true},
	    	{name:'id',hidden:true}
	    ];
		if (columns!=null&&columns.length>0){
			for ( var i = 0; i < columns.length; i++) {
				colModel.push({name: columns[i].code
					,label:columns[i].name
					, index: columns[i].code
					, width: 60
					,editable:true 
				});
			}	
		}
		colModel.push({label:'小计',name:'totalAmount'});
		$('#sizeDetail').jqGrid({
			datatype: 'local',
			width:780,
			height:200,
			altRows:true,
			gridview: true,
			onselectrow: false,
			colModel: colModel,
			rownumbers: true,//行号
			viewrecords: true,
			page: 1, //只有一页
			pgbuttons:false,
			pgtext:false,
			shrinkToFit:false,
            cellEdit: true,
            cellsubmit: 'clientArray',
            footerrow: true,
            userDataOnFooter: true,
			jsonReader: {
				root: 'rows',
				repeatitems : false,
				id:'id'
			},
			loadComplete: function(data){
			},
			loadError: function(xhr, status, error){
			},
			formatCellTitle:function(val,iRow, iCol){
				var key= colModel[iCol-1].name;
				var value = rowsOriginal[iRow-1][key];
				value = $.trim(value);
				var title='';
				if(value == ''){
					title = '';
				}
				var arrValue=value.split('/');
				if(arrValue !=null && arrValue != '' && arrValue.length > 0){
					if(system.USEABLE == 1){//启用可用库存
						title = "实际："+arrValue[0]+"<br/>可用："+arrValue[1];
					}else{
						title = "实际："+arrValue[0];
					}
				}else{
					title = '';
				}
				return title;
			},
			formatCell:function (rowid, cellname, value, iRow, iCol){//切换输入框前处理
				var grid=$('#sizeDetail');
				var selectCell=_self.selectCell;
				selectCell.rowid=rowid;
				selectCell.iRow=iRow;
				selectCell.iCol=iCol;
				selectCell.value=value;
				var arrValue=value.split('/');
				var inputValue;
				var realStock = chkRealStock.chkVal().join() ? true : false;
				var useableStock = chkUseableStock.chkVal().join() ? true : false;
				if(realStock && useableStock){
					if (arrValue!=''){
						selectCell.value0=arrValue[0];
						selectCell.value1=arrValue[1];
						selectCell.value2=arrValue[2];
					}else{
						selectCell.value0=0;
						selectCell.value1=0;
						selectCell.value2='';
					}	
					inputValue=selectCell.value2;
				}else if(realStock || useableStock){
					if (arrValue!=''){
						selectCell.value0=arrValue[0];
						selectCell.value1=arrValue[1];
					}else{
						selectCell.value0=0;
						selectCell.value1='';
					}
					inputValue=selectCell.value1;
				}else{
					selectCell.value0=arrValue[0];
					inputValue=selectCell.value0;
				}
				return inputValue;
			},
			onCellSelect: function(rowid,iCol,cellcontent,e){
			},
			beforeSaveCell :function(rowid, cellname, value, iRow, iCol){
				var selectCell=_self.selectCell;
				if (Validate.amount(value)){
					var vaildateStock=chkVaildateStock.chkVal().join() ? true : false;
					var realStock = chkRealStock.chkVal().join() ? true : false;
					var useableStock = chkUseableStock.chkVal().join() ? true : false;
					if(vaildateStock){
						var originalValue = rowsOriginal[iRow-1][colModel[iCol-1].name];//从原始数据中取得实际库存的值
						originalValue = $.trim(originalValue);
						var stockAmount = 0;
						var arrValue=originalValue.split('/');
						if(arrValue != null && arrValue != '' && arrValue.length > 0){
							stockAmount = arrValue[0];
						}
						if(parseInt(value)>parseInt(stockAmount)){
							Public.tips({type: 2, content : '库存不足！'});
							if(realStock && useableStock){
								value = _self.selectCell.value2;
							}else if(realStock || useableStock){
								value = _self.selectCell.value1;
							}else{
								value = _self.selectCell.value0;
							}
						}
					}
					var row = $('#sizeDetail').getRowData(rowid);
					var unitPrice = $("#unitPrice_show").val();
					if(isNaN(unitPrice)){
						unitPrice = $("#unitPrice").text()
					}
					var rebatePrice = $("#temp_rebatePrice").val();
					if($.trim(rebatePrice) == ''){
						rebatePrice = 0;
					}
					var sel_pi_type = chkGift.chkVal().join() ? 1 : 0;
					var updateData={
							pd_code:product.pd_code
							,pd_szg_code:product.pd_szg_code
							,cr_code:row.cr_code
							,br_code:row.br_code
							,sz_code:colModel[iCol-1].name
							,unitPrice:unitPrice
							,retailPrice:product.pd_sell_price
							,costPrice:product.pd_cost_price
							,rebatePrice:rebatePrice
							,sel_pi_type:sel_pi_type
							,amount:value==''?0:value
						};
					var newValue;
					if(realStock && useableStock){
						updateData.initAmount=selectCell.value2==''?0:selectCell.value2;
						if (selectCell.value0!=0
								||selectCell.value1!=0||value!=''){
							newValue=selectCell.value0+'/'+selectCell.value1+'/'+value;	
						}else{
							newValue='';
						}
					}else if(realStock || useableStock){
						updateData.initAmount=selectCell.value1==''?0:selectCell.value1;
						if (selectCell.value0!=0||value!=''){
							newValue=selectCell.value0+'/'+value;	
						}else{
							newValue='';
						}
					}else{
						updateData.initAmount=selectCell.value0==''?0:selectCell.value0;
						newValue = value;
					}
					updateDatas.add(updateData);
					return newValue;
					
					
				}else{
					return _self.selectCell.value;
				}
			},
			afterSaveCell:function(rowid, cellname, value, iRow, iCol){
				THISPAGE.gridTotal();
			},
			plusKeyDown:function(){
				$('#btnSave').click();
			}
	    });
		$('#sizeDetail').clearGridData();
		if (rows != null){		
			var hasBra=false;
			for(var i=0;i< rows.length;i++){
				$('#sizeDetail').jqGrid('addRowData', i + 1, rows[i]);
				if (!hasBra && $.trim(rows[i].br_code) != ''){
					hasBra=true;
				}
			}
			if (hasBra) {
				$('#sizeDetail').showCol("br_name");
            }else{
            	$('#sizeDetail').hideCol("br_name");
            }
	    	THISPAGE.reloadDetailGridData();
//	    	$('#sizeDetail').jqGrid("nextCell",1,1);//第一个输入框聚焦
	    	//Public.resizeSpecifyGrid("sizeDetail",125,445);
		}
	},
	reloadDetailGridData:function(){
		var grid=$('#sizeDetail')
		,rows=grid.getRowData()
		,colModel=grid.getGridParam('colModel');
		var realStock = chkRealStock.chkVal().join() ? true : false;
		var useableStock = chkUseableStock.chkVal().join() ? true : false;
		for(var rowIndex=0;rowIndex<rows.length;rowIndex++){
			var row=rows[rowIndex];
			for ( var colIndex = 6; colIndex < colModel.length-1; colIndex++) {
				var key= colModel[colIndex].name;
				var arrValue = null;
				var originalValue = null;
				if(row[key] != null && row[key] != ''){
					arrValue=row[key].split('/');
				}
				if(rowsOriginal[rowIndex][key] != null && rowsOriginal[rowIndex][key] != ''){
					originalValue = rowsOriginal[rowIndex][key].split('/');
				}
				var newValue = '';
				if(originalValue != null && originalValue != '' && originalValue.length > 0){
					if(originalValue[0] != null && originalValue[0] != '' && realStock){
						newValue += originalValue[0]+'/';
					}
					if(originalValue[1] != null && originalValue[1] != '' && useableStock){
						newValue += originalValue[1]+'/';	
					}
				}else{
					if(realStock){
						newValue += '0/';
					}
					if(useableStock){
						newValue += '0/';
					}
				}
				
				if (arrValue != null && arrValue != '' && arrValue.length > 0){
					newValue += arrValue[arrValue.length-1]
				}
				rows[rowIndex][key] = newValue;
				
			}
		}
		grid.clearGridData();
		for(var i=0;i< rows.length;i++){
			grid.jqGrid('addRowData', i + 1, rows[i]);
		}
		THISPAGE.gridTotal();
	},
	gridTotal:function(iRow,iCol){
		var grid=$('#sizeDetail')
			,rows=grid.getRowData()
			,rowFoot=grid.footerData()
			,colModel=grid.getGridParam('colModel');
		var realStock = chkRealStock.chkVal().join() ? true : false;
		var useableStock = chkUseableStock.chkVal().join() ? true : false;
		for(var rowIndex=0;rowIndex<rows.length;rowIndex++){
			var total1=0,total2=0,total3=0;
			var row=rows[rowIndex];
			for ( var colIndex = 6; colIndex < colModel.length-1; colIndex++) {
				var key= colModel[colIndex].name;
				var arrValue=row[key].split('/');
				if (arrValue.length > 0){
					if(arrValue[0] != null && arrValue[0]!='' && !isNaN(arrValue[0])){
						total1+=parseInt(arrValue[0]);	
					}					
					if(arrValue[1] != null && arrValue[1]!='' && !isNaN(arrValue[1])){ 
						total2+=parseInt(arrValue[1]);
					}
					if(arrValue[2] != null && arrValue[2]!='' && !isNaN(arrValue[2])){
						total3+=parseInt(arrValue[2]);	
					}
				}
			}
			
			if(realStock && useableStock){
				grid.setCell(row.id,'totalAmount',(total1+'/'+total2+'/'+total3));
			}else if(realStock || useableStock){
				grid.setCell(row.id,'totalAmount',(total1+'/'+total2));
			}else{
				grid.setCell(row.id,'totalAmount',(total1));
			}
		}
		rows=grid.getRowData();
		for ( var colIndex = 6; colIndex < colModel.length; colIndex++) {
			var total1=0,total2=0,total3=0;
			var key= colModel[colIndex].name;
			for ( var index = 0; index < rows.length; index++) {
	    		var row=rows[index];
				var arrValue=row[key].split('/');
				if (arrValue.length > 0){
					if(arrValue[0] != null && arrValue[0]!='' && !isNaN(arrValue[0])){
						total1+=parseInt(arrValue[0]);	
					}					
					if(arrValue[1] != null && arrValue[1]!='' && !isNaN(arrValue[1])){ 
						total2+=parseInt(arrValue[1]);
					}
					if(arrValue[2] != null && arrValue[2]!='' && !isNaN(arrValue[2])){
						total3+=parseInt(arrValue[2]);	
					}
				}
			}
			if(realStock && useableStock){
				if (total1==0&&total2==0&&total3==0){
					json= '{"'+colModel[colIndex].name+'":""}';
				}else{
					json= '{"'+colModel[colIndex].name+'":"'+(total1+'/'+total2+'/'+total3)+'"}';
				}	
			}else if(realStock || useableStock){
				if (total1==0&&total2==0){
					json= '{"'+colModel[colIndex].name+'":""}';
				}else{
					json= '{"'+colModel[colIndex].name+'":"'+(total1+'/'+total2)+'"}';
				}
			}else{
				json= '{"'+colModel[colIndex].name+'":"'+(total1)+'"}';
			}
			var jj=eval('('+json+')');
			grid.footerData("set",jj);
		}
		grid.footerData("set",{cr_name:'合计：'});
	},
	initTip:function(){
		var realStock = chkRealStock.chkVal().join() ? true : false;
		var useableStock = chkUseableStock.chkVal().join() ? true : false;
		if(realStock && useableStock){
			$('#spanDescribe').text('注:实际库存/可用库存/录入数量');
		}else if(realStock){
			$('#spanDescribe').text('注:实际库存/录入数量');
		}else if(useableStock){
			$('#spanDescribe').text('注:可用库存/录入数量');
		}else{
			$('#spanDescribe').text('注:录入数量');
		}
	},
	initEvent:function(){
		//实际库存点击
		$('#chkRealStock').click(function(){
			THISPAGE.initTip();
			THISPAGE.reloadDetailGridData();
		});
		//可用库存点击
		$('#chkUseableStock').click(function(){
			THISPAGE.initTip();
			THISPAGE.reloadDetailGridData();
		});
		//保存
		$('#btnSave').on('click', function(e){
			handle.save();
		});
		$('#btnExit').on('click', function(e){
			api.close();
		});
		$('#spanPriceMore').on('click',function(){
			var more=$('#spanPriceMore');
			var div=$('#divPriceMore');
			if (div.css('display')=='none'){
				var top = more.offset().top
					,left = more.offset().left;
				div.css(
					{
						'top':top+15
						,'left':left-10
						,'display':''
					}
				);	
			}else{
				div.css('display','none');
			}
		});
	}
};

var updateDatas={
	datas:[],
	add:function(updateData){
		var isExists=false;
		for (var i = 0; i < this.datas.length; i++) {
			var data = this.datas[i];
			if (data.pd_code == updateData.pd_code
					&& data.cr_code == updateData.cr_code
					&& data.sz_code == updateData.sz_code
					&& data.br_code == updateData.br_code) {
				data.amount = updateData.amount;
				isExists = true;
				break;
			}
		}
		if (!isExists){
			this.datas.push(updateData);
		}
	},
	get:function(){
		var datas=this.datas;
		var data;
		//去除没有更改的数据
		for ( var i = 0; i < datas.length; i++) {
			data=datas[i];
			if (data.initAmount==='' || (data.initAmount === 0 && data.amount != 0)){
				data.operate_type='add';
			}else if (data.initAmount==data.amount){
				datas.splice(i,1);
				i--;
			}else{
				data.operate_type='update';
			}
		}
//		if (datas.length>0){
//			oper.isRefresh=true;
//		}
		return datas;
	},
	clear:function(){
		this.datas = [];
	}
};

var Validate={
	amount:function(value){
		var reg=/^[0-9]*[0-9][0-9]*$/;
		return reg.test(value);
	}
};

THISPAGE.init();
